package com.caifenglin.utils.shiro;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.apache.shiro.util.ByteSource;

public class SecondRelam  extends AuthenticatingRealm  {

	/**
	 * 1、doGetAuthenticationInfo,获取认证消息，如果数据库中没有查询到指定数据，返回null，
	 * 如果得到正确的用户名和密码，则返回正确用户名和密码的对象
	 * 
	 * 2、AuthenticationInfo 可以使用SimpleAuthenticationInfo实现类，封装正确的用户名和密码
	 * 
	 * 3、token参数,就是我们需要认证的token
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		
		System.out.println("第2个relam正在工作-----------------------");
		SimpleAuthenticationInfo info = null;
		
		// 1、将token转换成UsernamePasswordToken
		UsernamePasswordToken upToken = (UsernamePasswordToken)token;
		// 2、获取用户名即可
		String userName = upToken.getUsername();
		// 3、查询数据库，是否存在指定用户名和密码的用户
		try {
			Class.forName("com.mysql.jdbc.Driver");
			String url = "jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
			Connection conn = DriverManager.getConnection(url, "test", "123");
			
			PreparedStatement ps = conn.prepareStatement("select * from user where name=?");
			ps.setString(1, userName);
			ResultSet rs = ps.executeQuery();
			if(rs.next()) {
				Object principal = userName;
				
				Object credentials = rs.getString(3);
				
				String realmName = this.getName();
				
				// 盐值加密
				ByteSource salt = ByteSource.Util.bytes(realmName);
				
				// 将数据库取出的密码加密
				SimpleHash sh = new SimpleHash("SHA1", credentials, salt, 1024);
				//SimpleHash sh = new SimpleHash("MD5", credentials, null, 1024);
				
				//info = new SimpleAuthenticationInfo(principal, credentials, realmName);
				//info = new SimpleAuthenticationInfo(principal, sh, realmName);
				
				info = new SimpleAuthenticationInfo(principal, sh, salt, realmName);
			} else {
				throw new AuthenticationException();
			}
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		
		// 4、如果查询到了，封装查询结果，返回给我们调用
		
		// 5、如果没有查询到，抛出一个异常
		return info;
	}


}
